// "我的页面"
import React, { useEffect, useRef, useState } from "react";
import { Avatar, Switch, Modal, Button, Input, message, Slider } from "antd";
// @ts-ignore
import { request } from '@/utils/request';
import Cropper from 'react-easy-crop';
import getCroppedImg from './_cropHelpers';
import { useOutletContext, useNavigate } from "react-router-dom";
import { useTheme } from "@/contexts/theme";
import { useI18n } from '@/utils/in18';
import { Select } from 'antd';

type OutletContextType = {
    user: any;
};

interface UserData {
    email: string;
    nickname: string;
    avatar_url: string;
}

const NAV_ITEMS = Object.freeze([
    { id: '我的作品', labelKey: 'mine.my_creation', path: '/my_work' },
    { id: '我的喜欢', labelKey: 'mine.my_likes', path: '/my_liked_persion' },
    { id: '我点赞的作品', labelKey: 'mine.liked', path: '/my_liked_workList' },
]);

const MinePage: React.FC = () => {
    const { user } = useOutletContext<OutletContextType>();
    const { dark, toggle } = useTheme();
    const { t, locale, setLocale } = useI18n();
    const navigate = useNavigate()
    const [userInformation, setUserInformation] = useState<any>(null);
    const [editVisible, setEditVisible] = useState(false);
    const [editingNickname, setEditingNickname] = useState<string>('');
    const [tempAvatarUrl, setTempAvatarUrl] = useState<string | null>(null); // preview (uploaded or local)
    const fileInputRef = useRef<HTMLInputElement | null>(null);
    const [uploading, setUploading] = useState(false);
    const [rawFile, setRawFile] = useState<File | null>(null);
    const [uploadedAvatarUrl, setUploadedAvatarUrl] = useState<string | null>(null);
    const [currentUserId, setCurrentUserId] = useState<number | null>(null);
    const [previewVisible, setPreviewVisible] = useState(false);
    const [uploadProgress, setUploadProgress] = useState<number>(0);
    const [crop, setCrop] = useState<{ x: number; y: number }>({ x: 0, y: 0 });
    const [zoom, setZoom] = useState<number>(1);
    const [croppedAreaPixels, setCroppedAreaPixels] = useState<any | null>(null);

    // 获取用户的信息 
    useEffect(() => {
        const raw = localStorage.getItem('userData');
        if (!raw) return;
        try {
            const parsed: Partial<UserData> = JSON.parse(raw);
            setUserInformation(parsed);
            const maybeId: any = (parsed as any)?.id ?? (user as any)?.id ?? null;
            if (maybeId) setCurrentUserId(Number(maybeId));
            console.log('email', parsed.email);
            console.log('nickname', parsed.nickname);
            console.log('avatar_url', parsed.avatar_url);
        } catch (e) {
            console.warn('解析 localStorage userData 失败', e);
        }
    }, []);

    // handle file select -> create temporary object URL for preview
    const onSelectFile = (file?: File) => {
        if (!file) return;
        setRawFile(file);
        const url = URL.createObjectURL(file);
        setTempAvatarUrl(url);
        // open preview modal for user to confirm upload
        setPreviewVisible(true);
        // reset crop/zoom when choosing new file
        setCrop({ x: 0, y: 0 });
        setZoom(1);
        setCroppedAreaPixels(null);
    };

    // trigger hidden file input
    const triggerFileInput = () => {
        if (!fileInputRef.current) return;
        fileInputRef.current.click();
    };

    // upload flow: send file to backend endpoint which handles storage
    const uploadCroppedAvatar = async (fileBlob: Blob | File, fileName = 'avatar.jpg') => {
        try {
            setUploading(true);
            setUploadProgress(0);
            const form = new FormData();
            form.append('file', fileBlob as Blob, fileName);
            form.append('userId', String(currentUserId ?? 123));

            // call backend upload endpoint
            const resp = await request.post('/api/upImage/uploadAvatar', form, {
            });
            console.log('resp', resp.data.data.url);

            if (!resp || !resp.data) throw new Error('上传接口返回异常');
            if (!resp.data.success) throw new Error(resp.data.message || '上传失败');

            const data = resp.data.data || {};
            const publicUrl = data.url || data.avatar_url || data.publicUrl || null;
            return publicUrl;
        } finally {
            setUploading(false);
        }
    };

    // Upload the currently selected rawFile (called when user confirms in preview modal)
    const confirmAndUploadSelected = async () => {
        if (!rawFile && !tempAvatarUrl) return;
        try {
            setUploading(true);
            let blobToUpload: Blob | null = null;
            let fileName = rawFile?.name || 'avatar.jpg';

            if (tempAvatarUrl && croppedAreaPixels) {
                // produce cropped blob from the preview URL and crop area
                const croppedBlob = await getCroppedImg(tempAvatarUrl, croppedAreaPixels);
                if (croppedBlob) {
                    blobToUpload = croppedBlob;
                    // prefer original file name if exists
                }
            }

            if (!blobToUpload) {
                // fallback to original file
                blobToUpload = rawFile as Blob;
            }

            const url = await uploadCroppedAvatar(blobToUpload as Blob, fileName);
            setUploadedAvatarUrl(url);
            setTempAvatarUrl(url);
            // close preview modal
            setPreviewVisible(false);
            // revoke object URL for original file to free memory
            try { URL.revokeObjectURL(tempAvatarUrl || ''); } catch { }
            setRawFile(null);
            message.success(t('messageApi.avatar_upload_success'));
        } catch (e) {
            console.error(e);
            message.error(t('messageApi.avatar_upload_failed'));
        } finally {
            setUploading(false);
        }
    };

    const onCropComplete = (_: any, croppedPixels: any) => {
        setCroppedAreaPixels(croppedPixels);
    };

    const [saving, setSaving] = useState(false);

    const handleSave = async () => {
        try {
            setSaving(true);
            const finalAvatarUrl = uploadedAvatarUrl || tempAvatarUrl || userInformation?.avatar_url || null;

            // call updateProfile
            const resp = await request.post('/api/auth/updateProfile', {
                nickname: editingNickname,
                avatar_url: finalAvatarUrl,
            });
            if (resp.data && resp.data.success) {
                const newData = resp.data.data;
                // update localStorage token and userData
                if (resp.data.token) localStorage.setItem('token', resp.data.token);
                localStorage.setItem('userData', JSON.stringify(newData));
                setUserInformation(newData);
                try { window.dispatchEvent(new CustomEvent('auth:updated')); } catch (e) { }
                message.success(t('messageApi.profile_save_success'));
                setEditVisible(false);
            } else {
                message.error(t('messageApi.profile_save_failed'));
            }
        } catch (e) {
            console.error(e);
            message.error(t('messageApi.profile_save_error'));
        } finally {
            setSaving(false);
        }
    };

    // 退出登录 - 先弹窗确认，再执行退出
    const [logoutConfirmVisible, setLogoutConfirmVisible] = useState(false);

    const performLogout = () => {
        try {
            localStorage.removeItem('token');
            localStorage.removeItem('userData');
            // 广播登出事件
            try { window.dispatchEvent(new CustomEvent('auth:logout')); } catch (e) { }
            // 清空页面内用户相关状态，确保 UI 立即更新
            setUserInformation(null);
            setCurrentUserId(null);
            setUploadedAvatarUrl(null);
            setTempAvatarUrl(null);
            setEditVisible(false);
            setPreviewVisible(false);

            message.success(t('messageApi.logout_success'));
        } catch (e) {
            console.error('logout error', e);
            message.error(t('messageApi.logout_failed'));
        }
    };

    const handleLogout = () => {
        setLogoutConfirmVisible(true);
    };

    return (
        <div className="w-full md:w-[50%] min-h-[var(--content-h)] sm:min-h-full px-4 py-4 pb-16 transition-colors mx-auto">
            {/* 用户信息板块 */}
            <div className="flex items-center gap-4 p-4 rounded-2xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-[#0b0b0b] shadow-sm">
                <Avatar src={userInformation?.avatar_url} size={56} className="flex-shrink-0 ring-1 ring-gray-100 dark:ring-[#1f1f1f]">
                    {userInformation?.nickname}
                </Avatar>
                <div className="flex-1 min-w-0">
                    <div className="text-base font-semibold text-gray-900 dark:text-gray-100 truncate">{userInformation?.nickname}</div>
                    <div className="text-xs text-gray-500 dark:text-gray-400 truncate mt-1">{userInformation?.email}</div>
                </div>
                {/* 修改按钮（仅登录用户可见） */}
                {userInformation ? (
                    <div>
                        <button aria-label="edit-profile" onClick={() => {
                            setEditingNickname(userInformation?.nickname || '');
                            setTempAvatarUrl(userInformation?.avatar_url || null);
                            setEditVisible(true);
                        }} className="p-1 rounded-md">
                            <svg viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="1489" width="20" height="20"><path d="M885.54 479.42c-24.18 0-43.79 19.61-43.79 43.79v318.22H184.91V184.59h325.38c24.18 0 43.79-19.61 43.79-43.79s-19.61-43.79-43.79-43.79H141.12c-24.18 0-43.79 19.61-43.79 43.79v744.42c0 24.18 19.61 43.79 43.79 43.79h744.42c24.18 0 43.79-19.61 43.79-43.79V523.21c0-24.18-19.61-43.79-43.79-43.79z" fill="#8a8a8a" p-id="1490"></path><path d="M600.88 221.56L400.07 453.72c-6.08 7.03-9.47 15.44-10.37 24.03l-66.62 229.64c-4.77 16.44 0.47 34.15 13.41 45.33a43.816 43.816 0 0 0 28.65 10.67c6.14 0 12.32-1.28 18.13-3.93l218.47-99.37c8.04-2.23 15.58-6.57 21.45-13.35l200.84-232.18 0.04-0.04c0.01-0.02 0.02-0.04 0.04-0.05l94.55-109.31a43.845 43.845 0 0 0 10.56-31.82c-0.86-11.59-6.24-22.36-15.03-29.96l-156.9-135.69c-18.32-15.82-45.95-13.81-61.77 4.47l-94.53 109.29c-0.02 0.02-0.04 0.03-0.06 0.06-0.02 0.01-0.03 0.03-0.05 0.05zM473.73 502.44l164.79-190.52 90.64 78.4-164.83 190.57-130.59 59.41 39.99-137.86z m259.38-299.87l90.66 78.38-37.3 43.12-90.64-78.4 37.28-43.1z" fill="#8a8a8a" p-id="1491"></path></svg>
                        </button>
                    </div>
                ) : null}
            </div>

            {/* 编辑弹窗 */}
            <Modal
                title={<div className="text-base font-semibold">{t('mine.edit_profile.title')}</div>}
                open={editVisible}
                onCancel={() => setEditVisible(false)}
                footer={null}
            >
                <div className="text-sm text-gray-500 mb-2">{t('mine.edit_profile.subtitle')}</div>

                <div className="flex flex-col items-center gap-3 py-4">
                    <div className="w-32 h-32 rounded-full overflow-hidden bg-gray-100 relative">
                        {tempAvatarUrl ? (
                            <img src={tempAvatarUrl} alt="avatar-preview" className="w-full h-full object-cover" />
                        ) : (
                            <Avatar size={128} src={userInformation?.avatar_url}>{userInformation?.nickname}</Avatar>
                        )}
                        <div className="absolute bottom-0 left-0 right-0 flex justify-center pb-1">
                            <button onClick={triggerFileInput} className="text-xs px-2 py-1 bg-white rounded opacity-90">{t('mine.edit_profile.upload_button')}</button>
                        </div>
                    </div>

                    {/* hidden file input */}
                    <input ref={fileInputRef} type="file" accept="image/*" className="hidden" onChange={(e) => {
                        const f = e.target.files && e.target.files[0];
                        if (f) onSelectFile(f);
                    }} />

                    {/* 选中文件后在单独的预览弹窗中展示 tempAvatarUrl，当前弹窗仅显示头像缩略与用户名 */}

                    <div className="w-full">
                        <div className="text-xs text-gray-500 mb-1">{t('mine.edit_profile.username_label')}</div>
                        <Input value={editingNickname} onChange={(e) => setEditingNickname(e.target.value)} />
                    </div>

                    <div className="w-full flex justify-end gap-2 mt-3">
                        <Button onClick={() => setEditVisible(false)}>{t('mine.edit_profile.cancel')}</Button>
                        <Button type="primary" loading={saving} onClick={handleSave}>{t('mine.edit_profile.save_changes')}</Button>
                    </div>
                </div>
            </Modal>

            {/* 选中文件后的预览确认弹窗：只展示 tempAvatarUrl、取消与确认按钮 */}
            <Modal
                title={null}
                open={previewVisible}
                onCancel={() => { setPreviewVisible(false); setTempAvatarUrl(null); setRawFile(null); }}
                footer={null}
            >
                <div className="flex flex-col items-center gap-4">
                    <div className="w-full flex flex-col items-center">
                        <div className="w-64 h-64 relative mb-3">
                            {tempAvatarUrl ? (
                                <div className="w-full h-full rounded-full overflow-hidden">
                                    <Cropper
                                        image={tempAvatarUrl}
                                        crop={crop}
                                        zoom={zoom}
                                        aspect={1}
                                        cropShape="round"
                                        showGrid={false}
                                        cropAreaStyle={{ border: '2px solid rgba(255,255,255,0.9)', borderRadius: '50%' }}
                                        onCropChange={setCrop}
                                        onZoomChange={setZoom}
                                        onCropComplete={onCropComplete}
                                    />
                                </div>
                            ) : (
                                <Avatar size={256} src={userInformation?.avatar_url} />
                            )}
                        </div>
                        {tempAvatarUrl && (
                            <div className="w-48 mb-2">
                                <Slider min={1} max={6} step={0.01} value={zoom} onChange={(v) => setZoom(v as number)} />
                            </div>
                        )}
                        <div className="flex gap-2">
                            <Button onClick={() => { setPreviewVisible(false); setTempAvatarUrl(null); setRawFile(null); }}>{t('mine.edit_profile.preview_cancel')}</Button>
                            <Button type="primary" loading={uploading} onClick={confirmAndUploadSelected}>{t('mine.edit_profile.preview_confirm')}</Button>
                        </div>
                    </div>
                </div>
            </Modal>

            {/* 功能导航栏 */}
            <div className="mt-4 grid grid-cols-3 py-4 px-2 rounded-2xl shadow-xl gap-3 border border-gray-200 dark:border-gray-700 ">
                {NAV_ITEMS.map((item) => (
                    <button
                        key={item.id}
                        onClick={() => { if (item.path) navigate(item.path); }}
                        className="p-3 rounded-lg bg-gray-50 dark:bg-[#0b0b0b] hover:bg-[#c2c2c2] dark:hover:bg-[#363636] border border-transparent dark:border-transparent text-gray-800 dark:text-gray-100 shadow-sm text-sm font-medium active:scale-[0.98] transition transform focus:outline-none focus-visible:ring-2 focus-visible:ring-[#15b8f7]"
                    >
                        {t(item.labelKey)}
                    </button>
                ))}
            </div>

            {/* 设置板块 */}
            <div className="mt-4 py-4 rounded-2xl bg-white border border-gray-200 dark:border-gray-700 dark:bg-[#0b0b0b]">
                {/* 切换主题按钮板块 */}
                <div className="flex px-4 items-center justify-between">
                    <div className="text-sm text-gray-800 dark:text-gray-100">{t('mine.switch_daynight')}</div>
                    <Switch checked={dark} onChange={toggle} />
                </div>

                {/* 切换语言按钮板块 */}
                <div className="mt-4 flex px-4 border-t border-gray-200 dark:border-gray-700 items-center justify-between py-4">
                    <div className="text-sm text-gray-800 dark:text-gray-100">{t('header.language_label')}</div>
                    <Select
                        className="flex-shrink-0"
                        size="small"
                        value={locale}
                        onChange={(val) => setLocale(val as any)}
                        options={[
                            { label: 'English', value: 'en' },
                            { label: '日本語', value: 'ja' },
                            { label: 'Español', value: 'es' },
                            { label: 'Français', value: 'fr' },
                            { label: 'Русский', value: 'ru' },
                        ]}
                        style={{ width: 140 }}
                    />
                </div>
            </div>

            {/* 退出登录的板块 如果用户没有登录则不展示  */}
            {userInformation ? (
                <Button className="w-full font-semibold mt-4 py-6 rounded-xl bg-[red]" type="primary" onClick={handleLogout}>{t('mine.logout')}</Button>
            ) : null}
            {/* 退出确认弹窗 */}
            <Modal
                title={null}
                open={logoutConfirmVisible}
                centered
                onCancel={() => setLogoutConfirmVisible(false)}
                footer={null}
                bodyStyle={{ padding: 0, borderRadius: 12, overflow: 'hidden' }}
                width={420}
            >
                <div>
                    <div className="flex flex-col items-center text-center gap-3">
                        <div className="w-14 h-14 rounded-full bg-red-50 dark:bg-red-900 flex items-center justify-center">
                            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zM11 7h2v6h-2V7zm0 8h2v2h-2v-2z" fill="#f44336" /></svg>
                        </div>
                        <div className="text-base font-semibold text-gray-900 dark:text-gray-100">{t('mine.logout_confirm_title')}</div>
                        <div className="text-sm text-gray-600 dark:text-gray-300">{t('mine.logout_confirm_message')}</div>
                    </div>

                    <div className="mt-6 flex items-center justify-end gap-3">
                        <Button onClick={() => setLogoutConfirmVisible(false)}>{t('mine.logout_cancel')}</Button>
                        <Button type="primary" danger onClick={() => { setLogoutConfirmVisible(false); performLogout(); }}>{t('mine.logout_confirm')}</Button>
                    </div>
                </div>
            </Modal>
        </div>
    );
};

export default MinePage;
